<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="退货单号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入退货订单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="销售单号" prop="relaSaleNo">
        <el-input
          v-model="queryParams.relaSaleNo"
          placeholder="请输入销售订单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="creator">
        <el-select
          v-model="queryParams.creator"
          clearable
          filterable
          placeholder="请选择销售人员"
          class="!w-240px"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择订单状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ERP_ORDER_RETURN_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker
          v-model="queryParams.orderTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <!-- <el-form-item label="销售退货总数量" prop="returnCount">
        <el-input
          v-model="queryParams.returnCount"
          placeholder="请输入销售退货总数量"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="销售退货总金额" prop="returnPrice">
        <el-input
          v-model="queryParams.returnPrice"
          placeholder="请输入销售退货总金额"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="退货后合计数量" prop="totalCount">
        <el-input
          v-model="queryParams.totalCount"
          placeholder="请输入退货后合计数量"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="退货后合计产品价格，单位：元" prop="totalProductPrice">
        <el-input
          v-model="queryParams.totalProductPrice"
          placeholder="请输入退货后合计产品价格，单位：元"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:sale-return:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:sale-return:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="退货单号" align="center" prop="no" min-width="120px" />
      <el-table-column label="关联销售订单号" align="center" prop="relaSaleNo" min-width="120px" />
      <el-table-column label="产品信息" align="center" min-width="180px">
        <template #default="scope">
          <div v-html="scope.row.productInfo"></div>
        </template>
      </el-table-column>
      <el-table-column label="总数量" align="center" prop="returnCount" width="80px" />
      <el-table-column
        label="下单时间"
        align="center"
        prop="orderTime"
        :formatter="dateFormatter"
        width="200px"
      />
      <el-table-column label="退货金额" align="center" prop="returnPrice" width="100px" />
      <el-table-column label="创建人" align="center" prop="creatorName" width="100px" />
      <el-table-column label="订单状态" align="center" width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_ORDER_RETURN_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="180px">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('detail', scope.row.id)">
            订单详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleViewStockIn(scope.row.no)"
            v-if="scope.row.status === 1"
          >
            查看入库单
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:sale-return:update']"
            v-if="scope.row.status === 0"
          >
            编辑
          </el-button>
          <el-button
            link
            type="success"
            @click="handleTransferIn(scope.row.id)"
            v-if="scope.row.status === 0"
            v-hasPermi="['erp:sale-return:update-status']"
          >
            转入库
          </el-button>
          <el-button
            link
            type="warning"
            @click="handleCancel(scope.row.id)"
            v-hasPermi="['erp:sale-return:delete']"
            v-if="scope.row.status === 0"
          >
            取消
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:sale-return:delete']"
            v-if="scope.row.status === 2"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <SaleReturnForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { SaleReturnApi, SaleReturnVO } from '@/api/erp/sale/return'
import { UserVO } from '@/api/system/user'
import * as UserApi from '@/api/system/user'
import SaleReturnForm from './SaleReturnForm.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { useRouter } from 'vue-router'
const router = useRouter() // 路由对象

/** ERP 销售退货 列表 */
defineOptions({ name: 'SaleReturn' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<SaleReturnVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  creator: undefined,
  relaSaleNo: undefined,
  status: undefined,
  orderTime: [],
  returnCount: undefined,
  returnPrice: undefined,
  totalCount: undefined,
  totalProductPrice: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const userList = ref<UserVO[]>([]) // 用户列表
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SaleReturnApi.getSaleReturnPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SaleReturnApi.deleteSaleReturn(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
/** 取消按钮操作 */
const handleCancel = async (id: number) => {
  try {
    // 删除的二次确认
    await message.cancelConfirm()
    // 发起删除
    await SaleReturnApi.cancelSaleReturn(id)
    message.success('取消成功!')
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SaleReturnApi.exportSaleReturn(queryParams)
    download.excel(data, 'ERP 销售退货.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 转入库操作 */
const handleTransferIn = async (id: number) => {
  try {
    // 二次确认
    await message.confirm('确认将该退货单转入库吗？')
    // 更新状态为待入库(1)
    await SaleReturnApi.updateSaleReturnStatus(id, 1)
    message.success('转入库成功')
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('转入库失败:', error)
  }
}

/** 查看入库单操作 */
const handleViewStockIn = (no: string) => {
  // 跳转到入库单页面，并携带退货单号作为查询参数
  router.push({
    path: `/erp/stock/in/${no}`
    // query: { orderNo: no }
  })
}

/** 初始化 **/
onMounted(async () => {
  userList.value = await UserApi.getSimpleUserList()
  getList()
})
</script>
